#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXSIZE 20

typedef enum {
    success,
    fail,
}status;

typedef struct {
    int *head;
    unsigned int length;
    unsigned int size;
}sqlist;

sqlist mylist;



status ListDelete(sqlist *list,unsigned int i,int *e)
{
    unsigned int k;
    if(list->length == 0){
        printf("empty list\n");
        return fail;
    }

    if(i < 1 || i > list->length){
        printf("delete wrong place\n");
        return fail;
    }

    if(e != NULL)
        *e = list->head[i-1]; 

    for(k = i;k < (list->length-1); k++){
        list->head[k-1] = list->head[k];
    }

    list->length--;

    return success;
}

status ListInsert(sqlist *list,unsigned int i,int e)
{
    unsigned int k;
    if(list->length == list->size){
        list->head = realloc(list->head,2*(list->size)*sizeof(int));
        list->size *= 2;
    }

    if(i < 1 || i > list->length ){
        printf("insert wrong place\n");
        return fail;
    }

    for(k = (list->length-1);k >= (i-1);k--){
        list->head[k+1] = list->head[k];
    }

    list->head[i-1] = e;

    list->length++;

    return success;   
}

unsigned int LocateElem(sqlist *list,int e)
{
    unsigned int i;
    for(i = 0;i < list->length;i++){
        if(list->head[i] == e )
            return (i+1);
    }

    return -1;
}

status GetElem(sqlist *list,unsigned int i,int *e)
{
    if(i > list->length || list->length == 0 || i < 1){
        printf("error\n");
        return fail;
    }

    *e = list->head[i-1];
    return success;
}

unsigned int ListLenth(sqlist *list)
{
    return list->length;
}

void ClearList(sqlist *list)
{
    if(list->length == 0){
        printf("the list already clear\n");
    }
  
    memset(list->head,0,(list->length*sizeof(int)));
}

status ListEmpty(sqlist *list)
{
    if(list->length != 0){
        return fail;
    }
  
    return success;
}


status InitList(sqlist *list)
{
    list->head = malloc(MAXSIZE*sizeof(int));
    if(list->head == NULL){
        printf("malloc fail!\n");
        return -1;
    }

    list->length = 0;
    list->size = MAXSIZE;
}

int main(int argc,char argv[])
{
    int k = 100000;
    int i;
    InitList(&mylist);

    for(i = 0;i < 10;i++){
        mylist.head[i] = i;
        mylist.length = 10;
    }
    
    while(k)
    {
        ListInsert(&mylist,2,100);
        k--;
    }

    printf("length:%u\nsize:%u\n",mylist.length,mylist.size);

    for(i = 0;i < mylist.size;i++){
        printf("mylist.head[%u]:%u\n",i,mylist.head[i]);
    }
    
    return 0;    
}

